#include<iostream>
using namespace std;
typedef long long ll;
ll x, y, p, q;
int gcd(int a, int b)
{
while (b ^= a ^= b ^= a %= b);
return a;
}
void simplify() {
int tmp = gcd(x, y);
x /= tmp;
y /= tmp;
}
ll adjust() {
ll num = 0;
ll tmp1 = p, tmp2 = q;
if (x * q< y* p )
{
if (q<y)
{
p = (y / q ) * p;
q = (y / q ) * q;
if (q<y)
{
q += tmp2;
p += tmp1;
}
}
if (p-x>q-y)
{
int need = p - x - q + y;
need = need / (tmp2 - tmp1);
p += need * tmp1;
q += need * tmp2;
if (p-x>q-y)
{
p += tmp1;
q += tmp2;
}
}
}
else
{
if (p < x)
{
q = (x / p ) * q;
p = (x / p ) * p;
if (p<x)
{
q += tmp2;
p += tmp1;
}
}
if (x - p > q - y)
{
int need = x - p - q + y;
need = need / (tmp2 - tmp1);
p += need * tmp1;
q += need * tmp2;
if (x - p > q - y)
{
p += tmp1;
q += tmp2;
}
}
}
num = q - y;
return num;
}
int main() {
ios::sync_with_stdio(false);
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> x >> y >> p >> q;
if (p == 0)
{
if (x == 0)
{
cout << 0<<endl;
continue;
}
cout << -1 << endl;
continue;
}
if (p == q)
{
if (x != y)
{
cout << -1 << endl;
}
else
{
cout << 0 << endl;
}
continue;
}
if (y == 0)
{
cout << q << endl;
continue;
}
if (x * q == y * p)
{
cout << 0 << endl;
continue;
}
else
{
x = adjust();
cout << x << endl;
}
}
}
1075B - Taxi drivers and Lyft | 1562A - The Miracle and the Sleeper |
1216A - Prefixes | 1490C - Sum of Cubes |
868A - Bark to Unlock | 873B - Balanced Substring |
1401D - Maximum Distributed Tree | 1716C - Robot in a Hallway |
1688B - Patchouli's Magical Talisman | 99A - Help Far Away Kingdom |
622B - The Time | 1688C - Manipulating History |
1169D - Good Triple | 1675B - Make It Increasing |
588A - Duff and Meat | 1541B - Pleasant Pairs |
1626B - Minor Reduction | 1680A - Minimums and Maximums |
1713A - Traveling Salesman Problem | 1713B - Optimal Reduction |
1710A - Color the Picture | 1686B - Odd Subarrays |
251A - Points on Line | 427C - Checkposts |
1159A - A pile of stones | 508A - Pasha and Pixels |
912A - Tricky Alchemy | 1249A - Yet Another Dividing into Teams |
1713C - Build Permutation | 1699A - The Third Three Number Problem |